import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:labcloud_app/model/user/user_model.dart';
import 'package:labcloud_app/widget/async_image.dart';

class Profile extends StatefulWidget {
  const Profile({super.key});

  @override
  State<Profile> createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  void _navigateToLoginRegister(BuildContext context) async {
    final result = await Navigator.pushNamed(context, '/login');

    // 如果从登录页面返回了结果，刷新页面
    if (result != null) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    final userModel = Provider.of<UserModel>(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('个人页'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const SizedBox(height: 50),
            // 头像
            CircleAvatar(
              radius: 50,
              backgroundImage: userModel.isLoggedIn && userModel.user != null && userModel.user!.avatarAddr != null
                ? null
                : const AssetImage('assets/images/default_avatar.png') as ImageProvider,
              child: userModel.isLoggedIn && userModel.user != null && userModel.user!.avatarAddr != null
                ? ClipOval(
                    child: AsyncImageWidget(
                      imageUrl: userModel.user!.avatarAddr!,
                    ),
                  )
                : userModel.isLoggedIn
                  ? null
                  : const Icon(
                      Icons.person,
                      size: 50,
                      color: Colors.white,
                    ),
            ),
            const SizedBox(height: 20),
            // 用户名或未登录提示
            Text(
              userModel.isLoggedIn && userModel.user != null ? userModel.user!.nickname ?? '未知用户' : '未登录',
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 30),

            // 功能按钮区域（较小的按钮）
            if (userModel.isLoggedIn) ...[
              // 订单状态按钮区域
              Container(
                width: 300,
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(15),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.2),
                      spreadRadius: 1,
                      blurRadius: 5,
                      offset: const Offset(0, 3),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildOrderButton(
                      icon: Icons.payment,
                      label: '未支付',
                      onPressed: () {
                        // 跳转到未支付订单页面
                        Navigator.pushNamed(context, '/order_main', arguments: 'non_pay');
                      },
                    ),
                    Container(
                      height: 40,
                      width: 1,
                      color: Colors.grey[300],
                    ),
                    _buildOrderButton(
                      icon: Icons.local_shipping,
                      label: '未送达',
                      onPressed: () {
                        // 跳转到未送达订单页面
                        Navigator.pushNamed(context, '/order_main', arguments: 'undelivered');
                      },
                    ),
                    Container(
                      height: 40,
                      width: 1,
                      color: Colors.grey[300],
                    ),
                    _buildOrderButton(
                      icon: Icons.check_circle_outline,
                      label: '未确认',
                      onPressed: () {
                        // 跳转到未确认订单页面
                        Navigator.pushNamed(context, '/order_main', arguments: 'unconfirmed');
                      },
                    ),
                    Container(
                      height: 40,
                      width: 1,
                      color: Colors.grey[300],
                    ),
                    _buildOrderButton(
                      icon: Icons.list,
                      label: '全部订单',
                      onPressed: () {
                        // 跳转到全部订单页面
                        Navigator.pushNamed(context, '/order_main');
                      },
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 30),

              Container(
                width: 300,
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(15),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.2),
                      spreadRadius: 1,
                      blurRadius: 5,
                      offset: const Offset(0, 3),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [

                    _buildFunctionButton(
                      icon: Icons.account_balance_wallet,
                      label: '钱包',
                      onPressed: () {
                        // 跳转到钱包页面
                        Navigator.pushNamed(context, '/wallet');
                      },
                    ),
                    Container(
                      height: 40,
                      width: 1,
                      color: Colors.grey[300],
                    ),
                    _buildFunctionButton(
                      icon: Icons.location_on,
                      label: '收货地址',
                      onPressed: () {
                        // 跳转到收货地址页面
                        Navigator.pushNamed(context, '/user_address'); // 更新了路由路径
                      },
                    ),
                    Container(
                      height: 40,
                      width: 1,
                      color: Colors.grey[300],
                    ),

                    _buildFunctionButton(
                      icon: Icons.favorite,
                      label: '收藏夹',
                      onPressed: () {
                        // TODO: 跳转到收藏夹页面
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('收藏夹功能待实现')),
                        );
                      },
                    ),
                  ],
                ),
              ),

            ],
            const SizedBox(height: 40),
            // 登录/注册按钮（合并为一个按钮）或退出登录按钮
            userModel.isLoggedIn
                ? ElevatedButton(
              onPressed: () {
                // 退出登录
                userModel.clearUser();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
              child: const Text(
                '退出登录',
                style: TextStyle(
                  fontSize: 16,
                ),
              ),
            )
                : ElevatedButton(
              onPressed: () {
                _navigateToLoginRegister(context);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
              child: const Text(
                '登录/注册',
                style: TextStyle(
                  fontSize: 16,
                ),
              ),
            ),

          ],
        ),
      ),
    );
  }

  // 构建功能按钮
  Widget _buildFunctionButton({
    required IconData icon,
    required String label,
    required VoidCallback onPressed,
  }) {
    return GestureDetector(
      onTap: onPressed,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 28,
            color: Colors.blue,
          ),
          const SizedBox(height: 3),
          Text(
            label,
            style: const TextStyle(
              fontSize: 10,
              color: Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  // 构建订单按钮（较大的按钮）
  Widget _buildOrderButton({
    required IconData icon,
    required String label,
    required VoidCallback onPressed,
  }) {
    return GestureDetector(
      onTap: onPressed,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 24,
            color: Colors.blue,
          ),
          const SizedBox(height: 3),
          Text(
            label,
            style: const TextStyle(
              fontSize: 10,
              color: Colors.black87,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}